#import <objc/runtime.h>
#import "UIBarItem+Extension.h"

@implementation UIBarItem (Extension)

- (NSString *)language
{
	return objc_getAssociatedObject(self, APPLANGUAGE);
}

- (void)setLanguage:(NSString *)language
{
	objc_setAssociatedObject(self, APPLANGUAGE, language, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
	self.title = L(language);
	
	[[NSNotificationCenter defaultCenter] removeObserver:self];
	if (language)
	{
		[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didLanguage) name:APPLANGUAGE object:nil];
	}
}

- (void)didLanguage
{
	self.title = L(self.language);
}

- (void)dealloc
{
	[[NSNotificationCenter defaultCenter] removeObserver:self name:APPLANGUAGE object:nil];
	objc_setAssociatedObject(self, APPLANGUAGE, nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

@end

@implementation UIBarButtonItem (Extension)

+ (id)initWithImage:(UIImage *)image target:(id)target action:(SEL)action
{
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithImage:image style:UIBarButtonItemStylePlain target:target action:action];
    return item;
}

+ (id)initWithTitle:(NSString *)title target:(id)target action:(SEL)action
{
    return [[UIBarButtonItem alloc] initWithTitle:(title ? title : @" ") style:UIBarButtonItemStylePlain target:target action:action];
}

+ (id)initBackWithTitle:(NSString *)title target:(id)target action:(SEL)action
{
	return [UIBarButtonItem initBackWithTitle:title target:target action:action image:IMG(@"ic_bar_back")];
}

+ (id)initBackWithTitle:(NSString *)title target:(id)target action:(SEL)action image:(UIImage *)image
{
	if (!image) image = [UIImage imageForColor:[UIColor clearColor] size:CGSizeMake(20, 60)];
	
    if (!title)
    {
		UIBarButtonItem *item = [UIBarButtonItem initWithImage:image target:target action:action];
        //item.imageInsets = UIEdgeInsetsMake(2, -8, 0, 0);
        return item;
    }
    
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:title style:UIBarButtonItemStylePlain target:target action:action];
    [item setBackgroundImage:[image resizableImageWithCapInsets:UIEdgeInsetsMake(0, image.size.width, 0, 0)] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
		
    return item;
}

+ (id)initWithSystemItem:(UIBarButtonSystemItem)systemItem target:(id)target action:(SEL)action
{
	UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:systemItem target:target action:action];
	
	return item;
}

@end
